var express = require('express');
var path = require('path');
const JwtToekn = require('./util/JwtToken')


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// token 中间件处理
app.use((req, res, next) => {
    //中间件要执行的代码
    const white = ['/user/login', '/user/register'];
    // 是否是白名单
    if (white.indexOf(res.path) === -1) {
        // 解析 token 判断用户是否登陆
        let result = JwtToekn.decrypt(req.headers.token);
        if (!result.token) {
            res.json({
                code: 401,
                msg: '登陆失效'
            })
        } else {
            next();
        }
    }

})


app.use(express.json());
app.use(express.urlencoded({
    extended: false
}));

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/user', usersRouter);

module.exports = app;